<?php
/**
 * @Name  : BaseSearch.php
 * @Author: yashuai<1762910894@qq.com>
 */

namespace App\Http\Search;

use HugCode\PhpUnits\InstanceTool;
use Illuminate\Database\Eloquent\Builder;

class BaseSearch
{

    use InstanceTool;

    protected $order_field = [];

    /**
     * @Desc   查询分页列表
     * @param  $query
     * @param bool|array $order ['field', 'type']
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    protected function pageList($query, $order = false)
    {
        // 排序
        $orderField = _array_field($this->params, 'OrderField');
        $orderType  = _array_field($this->params, 'OrderType');
        if (!empty($orderField) && !empty($orderType)
            && in_array($orderType, ['asc', 'desc'])
            && in_array($orderField, $this->order_field)
        ) {
            $query->orderBy($orderField, $orderType);
        } else if (!empty($order)) {
            $query->orderBy($order[0], $order[1]);
        }

        if (!_array_field($this->params, 'NoPage')) {
            $size = _array_field($this->params, 'Size', 20);
            $page = _array_field($this->params, 'Page', 1);

            $count = $query->count();
            if (empty($count)) {
                return $this->emptyList();
            }
            $list = $query->limit($size)->offset(($page - 1) * $size)->get()->toArray();
        } else {
            $list  = $query->get()->toArray();
            $count = count($list);
        }
        return compact('count', 'list');
    }

    /**
     * @Desc 列表返回空
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    protected function emptyList()
    {
        return ['count' => 0, 'list' => []];
    }

    /**
     * @Desc   下拉框数据
     * @param Builder $query
     * @param string $value
     * @param string $label
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    public function selectBase(Builder $query, string $label, string $value)
    {
        $list = $query->select([$value, $label])->get()->toArray();
        if (empty($list)) {
            return [];
        }
        $result = [];
        foreach ($list as $val) {
            $result[] = [
                'value' => $val[$value],
                'label' => $val[$label],
            ];
        }

        return $result;
    }
}
